// pages/profile/profile.js
import { userBehavior } from '../../behaviors/userBehavior'

import {
  request, upload,validator
} from '../../utils/requestUtils';

Page({
  behaviors: [userBehavior],

  // 页面的初始数据
  data: {
  },

  //修改昵称
  onChange(event) {
    console.log('event.detail', event.detail)
    switch (event.currentTarget.dataset['input']) {
      case 'nickName':
        this.setData({
          "userInfo.nickName": event.detail,
        })
        break;
      case 'phonenumber':
        this.setData({
          "userInfo.phonenumber": event.detail,
        })
        break;
    }
  },

  //保存用户信息
  async saveConfirm(e) {
    let postMpdel = JSON.parse(JSON.stringify(this.data.userInfo))
    const { valid } = await this.validator(postMpdel)
    if (!valid) return
    const result = await request({
      url: `/system/user/profile`,
      method: "PUT",
      data: {
        id: this.data.userInfo.id,
        avatar:this.data.userInfo.avatar,
        nickName: this.data.userInfo.nickName,
        phonenumber:this.data.userInfo.phonenumber
      }
    })
    if (result.data.code == 200) {
    
      this.setUserInfo(this.data.userInfo)
      wx.navigateBack({
        delta: 1
      })
    }
  },

  // 数据校验
  validator(params) {
    console.log('params', params)
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    const rules = {
      nickName: [
        { required: true, message: '请输入昵称' },
        { pattern: nameRegExp, message: '昵称不合法' }
      ],
      phonenumber: [
        { required: true, message: '请输入手机号' },
        { pattern: phoneReg, message: '手机号不合法' }
      ]
    }
    return validator(params,rules)
  },

  // 更新用户头像
  async chooseAvatar(event) {
    const { avatarUrl } = event.detail
    const result = await upload({ url: avatarUrl }, 'file')
    const data = JSON.parse(result);
    this.setData({
      'userInfo.avatar': data.url
    })
  },
})
